package com.xlh.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.DelayQueue;

/**
 * 流水登陆监听
 * <p>
 * Created by lx on 2018/7/4.
 */
@Component
public class OperationLoginListener implements ApplicationListener<ContextRefreshedEvent> {

    private Logger logger = LoggerFactory.getLogger(OperationLoginListener.class);

    private static DelayQueue<OperationLoginTask> delayQueue = new DelayQueue<>();

    @Autowired
    @Qualifier("taskRetryExecutor")
    private ThreadPoolTaskExecutor taskRetryExecutor;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            new Thread(() -> {
                while (true) {
                    try {
                        taskRetryExecutor.execute(delayQueue.take());
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }).start();
        }
    }

    public static DelayQueue<OperationLoginTask> getDelayQueue() {
        return delayQueue;
    }
}
